
<!--
*  2021-03-15
*  余纱退回
-->
<template>
  <div id="app" class="home" tabindex="-1" ref="tabDiv">
    <!-- 头部导航 -->
    <div class="wrapper" ref="wrapper" :style="{ top: top }">
      <van-nav-bar title="余纱退回"></van-nav-bar>
      <div class="home-login">
        <div class="home-login__logo"></div>
        <van-button @click="onClickLeft">扫码登陆</van-button>
      </div>
    </div>
    <p>版本号：V1.1.3</p>

    <!-- 登陆弹窗提示 -->
    <van-dialog
      v-model="show"
      :title="title"
      show-cancel-button
      confirm-button-text="登陆"
      @cancel="onClickCancel"
      @confirm="onGetLoginConfirm"
    >
      <van-cell title="姓名" :value="realName" />
      <van-cell title="手机号" :value="mobile" />
    </van-dialog>
  </div>
</template>

<script>
import { openWin, randomStr } from "@/utils/index";
import { getLoginList } from "@/api/login";
import {
  removeInfo
} from "@/utils/auth";

export default {
  name: "Home",
  data() {
    return {
      timer: null,
      code: "",
      lastTime: "",
      nextTime: "",
      lastCode: "",
      nextCode: "",
      loading: false,
      top: 0,
      time: null,
      ip: "",
      loginList: [],
      show: false,
      title: '',
      realName: '',
      mobile: '',
      no: '',
      pwd: '',
      params: {}
    };
  },
  created() {
    const that = this;
    removeInfo();
    if (process.env.NODE_ENV === "production") {
      that.$nextTick(() => {
        that.getUserIP((ip) => {
          that.ip = ip;
        });
        // 余纱退回
        that.onGetLoginList();
        // 余纱退回
        // 监听页面消失的时候，关掉页面就可以了
        window.api.addEventListener(
          {
            name: "viewdisappear",
          },
          function () {
            // clearInterval(that.time)
            window.removeEventListener("keydown", that.onClickKeydown);
            that.time = null;
            window.api.closeWin();
          }
        );
      });
    } else {
      window.apiready = function () {
        that.getUserIP((ip) => {
          that.ip = ip;
        });
        // 余纱退回
        that.onGetLoginList();
        // 余纱退回
        // 监听页面消失的时候，关掉页面就可以了
        window.api.addEventListener(
          {
            name: "viewdisappear",
          },
          function () {
            // clearInterval(that.time)
            that.time = null;
            window.removeEventListener("keydown", that.onClickKeydown);
            window.api.closeWin();
          }
        );
      };
    }
  },
  methods: {
    onGetLoginList() {
      const that = this;
      getLoginList("", function (res) {
        window.removeEventListener("keydown", that.onClickKeydown);
        that.loginList = res;
      });
    },
    // 扫码
    onClickLeft() {
      this.loading = false;
      if (!this.loading && this.loginList.length != 0) {
        this.onWatchEnter();
        this.loading = true;
        this.$toast({
          type: "loading",
          message: "请扫码",
          forbidClick: true,
          duration: 20000,
        });
      } else {
        this.onGetLoginList()
      }
    },
    // 监听扫码时间
    onWatchEnter() {
      this.code = "";
      this.lastTime = "";
      this.nextTime = "";
      this.lastCode = "";
      this.nextCode = "";
      window.addEventListener("keydown", this.onClickKeydown);
    },
    // 监听事件
    onClickKeydown(e) {
      const that = this;
      if (!that.show) {
        that.$toast({
          type: "loading",
          message: "二维码解析中",
          forbidClick: true,
          duration: 20000,
        });
        console.log(e);
        if (window.event) {
          // IE
          that.nextCode = e.keyCode;
        } else if (e.which) {
          // Netscape/Firefox/Opera
          that.nextCode = e.which;
        }
        if (e.which === 13) {
          if (that.code.length < 3) return; // 手动输入的时间不会让code的长度大于2，所以这里只会对扫码枪有
          that.$refs.tabDiv.focus();
          that.$toast.clear();
          console.log("扫码结束");
          console.log(that.code.replace(/Shift/g, ""));
          that.loginInfo = that.code.replace(/Shift/g, "");
          if (that.loading) {
            // 获取到扫码枪输入的内容，登陆

            let loginIndex = that.loginInfo.indexOf(",type=login,");
            if (loginIndex == -1) {
              that.$toast.fail("二维码异常");
              return false;
            }
            let no = that.loginInfo.substr(0, loginIndex);
            let pwd = that.loginInfo.substr(
              loginIndex + 12,
              that.loginInfo.length - 1
            );
            let index = that.loginList.findIndex((item) => item.no === no);
            if (index == -1) {
              that.$toast.fail("请联系管理员配置权限");
              return false;
            }
            that.$toast({
              type: "loading",
              message: "获取登陆信息",
              duration: 1000,
              onClose: () => {
                that.loginInfo = "";
                that.onGetLogin({
                  no: no,
                  realName: that.loginList[index].realName,
                  mobile: that.loginList[index].mobile,
                  pwd: pwd,
                });
              },
            });


            // let obj = that.isJSON(that.loginInfo);
            // let index = that.loginList.findIndex(
            //   (item) => item.id == obj.workerId
            // );
            // if (index !== -1) {
            //   that.$toast({
            //     type: "loading",
            //     message: "获取登陆信息",
            //     duration: 1000,
            //     onClose: () => {
            //       that.loginInfo = "";
            //       that.onGetLogin(that.loginList[index]);
            //     },
            //   });
            // } else {
            //   that.loginInfo = "";
            //   that.$toast.fail("当前用户无操作，请确认");
            // }
          }
          that.code = "";
          that.lastCode = "";
          that.lastTime = "";
          return;
        }
        that.nextTime = new Date().getTime();
        if (!that.lastTime && !that.lastCode) {
          console.log("扫码开始。。。");
          that.code += e.key;
        }
        if (
          that.lastCode &&
          that.lastTime &&
          that.nextTime - that.lastTime > 500
        ) {
          // 当扫码前有keypress事件时,防止首字缺失
          console.log("防止首字缺失。。。");
          that.code = e.key;
        } else if (that.lastCode && that.lastTime) {
          console.log("扫码中。。。");
          that.code += e.key;
        }
        that.lastCode = that.nextCode;
        that.lastTime = that.nextTime;
      }
    },
    isJSON(str) {
      let obj = "";
      if (typeof str == "string") {
        try {
          obj = JSON.parse(str);
          return obj;
        } catch (e) {
          return false;
        }
      }
      return obj;
    },
    // 点击 登录
    onGetLogin(list) {
      const that = this;
      that.no = list.no;
      that.title = "确认" + list.no + "登陆? ";
      that.realName = list.realName;
      that.mobile = list.mobile;
      that.pwd = list.pwd;
      that.show = true;
    },
    // 登录
    onGetLoginConfirm() {
      window.removeEventListener("keydown", this.onClickKeydown);
      const that = this;
      let param = {
        no: that.no,
        pwd: that.pwd,
        platform: 2,
        captcha: randomStr(),
      };
      that.$store.dispatch("user/login", param).then(() => {
        openWin("yarn-list");
      });
    },
    // 取消登陆
    onClickCancel() {
      window.removeEventListener("keydown", this.onClickKeydown);
      this.no = "";
      this.realName = "";
      this.mobile = "";
      this.pwd = "";
      this.show = false;
    },
    // 获取ip
    getUserIP(onNewIP) {
      let MyPeerConnection =
        window.RTCPeerConnection ||
        window.mozRTCPeerConnection ||
        window.webkitRTCPeerConnection;
      let pc = new MyPeerConnection({
        iceServers: [],
      });
      let noop = () => {};
      let localIPs = {};
      let ipRegex =
        /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;
      let iterateIP = (ip) => {
        if (!localIPs[ip]) onNewIP(ip);
        localIPs[ip] = true;
      };
      pc.createDataChannel("");
      pc.createOffer()
        .then((sdp) => {
          sdp.sdp.split("\n").forEach(function (line) {
            if (line.indexOf("candidate") < 0) return;
            line.match(ipRegex).forEach(iterateIP);
          });
          pc.setLocalDescription(sdp, noop, noop);
        })
        .catch(() => {});
      pc.onicecandidate = (ice) => {
        if (
          !ice ||
          !ice.candidate ||
          !ice.candidate.candidate ||
          !ice.candidate.candidate.match(ipRegex)
        )
          return;
        ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
      };
    },
  },
};
</script>

<style lang="scss">

.home {
  .wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    top: 0;
    .van-nav-bar__left,
    .van-nav-bar__right {
      span {
        font-size: 30px;
      }
    }
    .home-login {
      width: 100%;
      height: 500px;
      display: flex;
      flex-direction: column;
      align-items: center;
      position: relative;
      .home-login__logo {
        width: 187px;
        height: 180px;
        // @include bg-image("./../../assets/img/fns");
        @include bg-image("./../../../assets/img/fns");
        margin: 100px 0;
      }
      .van-button {
        width: 480px;
        height: 80px;
        margin: 20px;
        background: #1677ff;
        border-radius: 2px;
        font-size: 32px;
        color: #ffffff;
        position: relative;
        z-index: 300;
      }
      .home-input {
        width: 470px;
        height: 80px;
        line-height: 80px;
        // position: absolute;
        // bottom: 20px;
        // z-index: 120;
      }
    }
  }
  p {
    padding-left: 10px;
    position: fixed;
    bottom: 0;
    left: 50%;
    margin-left: -60px;
    line-height: 60px;
  }
  .van-dialog__content {
    margin: 40px 0;
  }
}
</style>
